<!DOCTYPE html>
<html lang="en">

	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>鼠标悬停下拉菜单</title>
		<style>
			nav {
				background-color: skyblue;
				padding: 10px;
			}

			.menu {
				list-style-type: none;
				margin: 0;
				padding: 0;
				display: flex;
			}

			.menu li {
				position: relative;
				margin-right: 70px;
				list-style-type: none;
			}

			.menu span {
				color: white;
				cursor: pointer;/*变手指*/
				padding: 5px 10px;
				
			}

			.dropdown-content {
				display: none;
				position: absolute;
				background-color: black;
				min-width: 150px;
				box-shadow: 0 
                4px 8px rgba(0, 0, 0, 0.2);/*阴影*/
				z-index: 1;
			}

			.dropdown-content li {
				padding: 8px 10px;
			}

			.dropdown-content a {
				text-decoration: none;
				color: white;
				display: block;
			}

			.dropdown-content a:hover {
				background-color: #ddd;
			}
            
		</style>
	</head>

	<body>
		<nav>
			<ul class="menu">
				<li class="dropdown">
					<span>手机</span>
					<ul class="dropdown-content">
						<a href="">华为</a>
						<a href="">苹果</a>
						<a href="">小米</a>
					</ul>
				</li>
				<li class="dropdown">
					<span>运动品牌</span>
					<ul class="dropdown-content">
						<a href="">耐克</a>
                        <a href="">阿迪</a>
                        <a href="">puma</a>
					</ul>
				</li>
				<li class="dropdown">
					<span>人工智能</span>
					<ul class="dropdown-content">
						<a href="">豆包</a>
                        <a href="">小爱同学</a>
                        <a href="">Siri</a>
					</ul>
				</li>
				<li class="dropdown">
					<span>小吃</span>
					<ul class="dropdown-content">
						<a href="">臭豆腐</a>
						<a href="">面筋</a>
						<a href="">肉串</a>
					</ul>
				</li>
				<li class="dropdown">
					<span>电脑</span>
					<ul class="dropdown-content">
						<a href="">联想</a>
						<a href="">戴尔</a>
						<a href="">惠普</a>
					</ul>
				</li>
			</ul>
		</nav>
		<script>
			// 获取所有带有dropdown类的菜单项
			const dropdownItems = document.querySelectorAll('.dropdown');

			// 遍历每个菜单项，添加鼠标悬停和移开的事件监听器
			dropdownItems.forEach(item => { //forEach简化遍历数组
				// 鼠标悬停时显示下拉菜单
				item.addEventListener('mouseenter', function() {
					const dropdownContent = this.querySelector('.dropdown-content');
					dropdownContent.style.display = 'block';
				});

				// 鼠标移开时隐藏下拉菜单
				item.addEventListener('mouseleave', function() {
					const dropdownContent = this.querySelector('.dropdown-content');
					dropdownContent.style.display = 'none';
				});
			});
		</script>
	</body>

</html>